﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Threading;

public class ClientProxy : ClientBase
{
    private TcpServerCore core;

    public ClientProxy(Socket socket, TcpServerCore core, bool isPacketDecode)
    {
        this.clientSocket = socket;
        this.core = core;
        this.isPacketDecode = isPacketDecode;

        mux.WaitOne();
        try
        {
            clientSocket.BeginReceive(readBuff, 0, MAX_BUFF_LENGTH, SocketFlags.None, ReceiveCb, null);
            mux.ReleaseMutex();
        }
        catch (Exception ex)
        {
            mux.ReleaseMutex();
            CoreEvent ce = new CoreEvent();
            ce.eventType = NetEventType.COMM_START_ASYNC_RECEIVE_THREAD_FAILED;
            ce.log = ex.Message;
            NetCore.AddEvent(ce);
        }
    }

    /// <summary>
    /// 断开连接
    /// </summary>
    public override void Close()
    {
        mux.WaitOne();
        if (clientSocket.Connected)
        {
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
        }
        mux.ReleaseMutex();
    }
    /// <summary>
    /// 断开连接 并清理
    /// </summary>
    protected override void Close(NetEventType type, string log)
    {
        Close();
        core.RemoveClient(type, log, this);
    }

    public override int Send(byte[] msg)
    {
        if (clientSocket == null) return 0;
        try
        {
            return clientSocket.Send(msg);
        }
        catch (Exception ex)
        {
            NetCore.LogWarning(ex);
        }
        return 0;
    }
}
